<template>
    <div id="leftup" style="width: 600px; height: 400px;"></div>
  </template>
  
  <script setup>
  import { onMounted, defineProps, watch, nextTick } from 'vue';
  import * as echarts from 'echarts';
  
  // 定义 props，接收父组件传递的数据
  const props = defineProps({
    childData1: Array
  });
  
  let myChart = null; // 存储 ECharts 实例
  
  const initECharts = () => {
    const echartsContainer = document.getElementById("leftup");
    if (myChart) {
      // 如果已经存在 ECharts 实例，则先销毁它
      myChart.dispose();
    }
    // 初始化 ECharts 实例
    myChart = echarts.init(echartsContainer);
    // 检查childData1是否已定义
    if (!props.childData1 || props.childData1.length === 0) {
      console.warn('childData1 is not ready yet.');
      return; // 如果数据未准备好，直接返回不执行后续逻辑
    }

    const years = [];
    const totalSales = [];
    props.childData1.forEach(item => {
      years.push(item.year);
      totalSales.push(item.total_sales);
    });
    const option = {
      tooltip: {
        trigger: 'axis',
        backgroundColor:'rgba(255,255,255,0.2)',
        axisPointer: {
            type: 'shadow',
            label: {
                show: true,
                backgroundColor: '#3259B8'
            }
        }
    },
      color: ['#66CCFF'],
      xAxis: [{
        type: 'category',
        gridIndex: 0,
        position: 'bottom',
        axisLabel: { interval: 0 },
        data: years,
        show: false,
        boundaryGap: true
      }],
      yAxis: [{
        name:'销售量',
        splitLine: {show: false},
        axisLine: {
            lineStyle: {
                color: '#ccc',
            }
        },
        axisLabel:{
            formatter:'{value} Ha',
        }
    },
        ],
        dataZoom: [{
        type: 'slider',
        show: true,
        xAxisIndex: [0, 1, 2, 3],
        start: 50,
        end: 100
      }, {
        type: 'inside',
        xAxisIndex: [0, 1, 2, 3]
      }],
      series: [{
        type: 'line',
        data: totalSales,
        yAxisIndex: 0,
        symbol: 'none',
        smooth: true
      }]
    };
    myChart.setOption(option);
  };
  
  // 修改onMounted钩子
  onMounted(async () => {
    await nextTick(); // 等待DOM更新
    initECharts();
  });
  
  // 修改watcher回调，添加async并使用nextTick
  watch(() => props.childData1, async () => {
    await nextTick(); // 等待DOM更新
    initECharts();
  }, { immediate: true });
  
  </script>
  
  <style scoped>
  /* 这里放置组件的样式 */
  </style>
  